package mq;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

/**
 * Created by yijy on 2017/6/16.
 */
public class Customer {
    public static void main(String[] args) throws MQClientException {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group_consumer");
        consumer.setNamesrvAddr("120.26.130.187:9876");
        consumer.setInstanceName("consumer");

        /**
         * 订阅指定Topic下tags分别等于TagA或TagB的消息
         */
        consumer.subscribe("TopicTest","TagA || TagB");
        /**
         * 订阅指定Topic下所有消息</br>
         * 注意：一个consumer可以订阅多个Topic
         */
        consumer.subscribe("TopicTest1","*");
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            //默认list里消息只有一条，可以通过consumeMessageBatchMaxSize参数来批量接收消息
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(
                    List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                System.out.println(Thread.currentThread().getName()+""+list.size());
                MessageExt msg = list.get(0);
                if("TopicTest".equals(msg.getTopic())){
                    if(null!=msg.getTags() && "TagA".equals(msg.getTags())){
                        System.out.println(new String(msg.getBody()));
                    }else if(null!=msg.getTags() && "TagB".equals(msg.getTags())){
                        System.out.println(new String(msg.getBody()));
                    }

                }else if("TopicTest1".equals(msg.getTopic())){
                    System.out.println(new String(msg.getBody()));
                }

                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        /**
         * consumer在使用前必须先调用start实例化,初始化一次即可<br>
         */
        consumer.start();
        System.out.println("consumer started!");
    }
}
